package com.block.datapush.service.apipush;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.block.common.model.dto.ThirdInfoDTO;
import com.block.common.model.param.PushApiKeyParam;
import com.block.common.service.IApplicationInfoService;
import com.block.common.service.LogFactory;
import com.block.common.service.merchant.IMerchantThirdBaseInfoService;
import com.block.datapush.enums.PushStatusEnum;
import com.block.datapush.model.PushQueryParam;
import com.block.datapush.model.dto.NoticeParamDTO;
import com.block.datapush.model.result.ProtocolParamResult;
import com.block.datapush.model.result.PushApiResult;
import com.block.datapush.service.IPushApiService;
import com.block.datapush.service.apipush.utils.JuYouHuaSsqUtil;
import com.block.datapush.service.apipush.utils.QiDaiAesUtil;
import com.block.db.entity.MemberSourceInfo;
import com.block.db.entity.MerchantBaseInfo;
import com.block.db.mapper.MerchantThirdBaseInfoMapper;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 桔铀花双授权
 */
@Service
public class JuYouHuaSsqApiService implements IPushApiService {

    private static final Logger log = LogFactory.getPushLog();

    @Autowired
    IMerchantThirdBaseInfoService merchantThirdBaseInfoService;
    @Autowired
    IApplicationInfoService applicationInfoService;
    @Autowired
    MerchantThirdBaseInfoMapper merchantThirdBaseInfoMapper;

    @Override
    public PushApiResult checkUser(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        String queryUrl = pushApiKeyParam.getCheckUrl();

        String mobileMd5 = memberSourceInfo.getMobileMd5().toLowerCase();

        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("encryptMobile", mobileMd5);
        bizMap.put("cnName", memberSourceInfo.getRealname());
        bizMap.put("province", memberSourceInfo.getProvince());
        bizMap.put("city", memberSourceInfo.getCity());
        bizMap.put("age", memberSourceInfo.getAge());
        bizMap.put("sex", memberSourceInfo.getSex());
        bizMap.put("amount", JuYouHuaSsqUtil.getloan(memberSourceInfo.getLoanAmount()));
        bizMap.put("loanTime", JuYouHuaSsqUtil.getloantime(memberSourceInfo.getLoanTime()));
        bizMap.put("education", JuYouHuaSsqUtil.getxueli(memberSourceInfo.getXueli()));
        bizMap.put("job", JuYouHuaSsqUtil.getjob(memberSourceInfo.getGongzuo()));
        bizMap.put("salaryPay", 1);
        bizMap.put("licenseTime", 0);
        bizMap.put("shebao", JuYouHuaSsqUtil.getSocialInsurance(memberSourceInfo.getShebao()));
        bizMap.put("gongjijin", JuYouHuaSsqUtil.getGjj(memberSourceInfo.getGjj()));
        bizMap.put("house", JuYouHuaSsqUtil.getHouse(memberSourceInfo.getHouse()));
        bizMap.put("vehicle", JuYouHuaSsqUtil.getCar(memberSourceInfo.getCar()));
        bizMap.put("insurance", JuYouHuaSsqUtil.getbaodan(memberSourceInfo.getBaoxian()));
        bizMap.put("zhima", JuYouHuaSsqUtil.getZhimaScore(memberSourceInfo.getZhima()));

        String aesKey = pushApiKeyParam.getApiKey();
        String body = QiDaiAesUtil.encrypt(JSON.toJSONString(bizMap), aesKey);
        String orgId = pushApiKeyParam.getApiCode();
        Long timestamp = System.currentTimeMillis();
        String sign = SecureUtil.md5(StrUtil.format("body={}&orgId={}&timestamp={}&secret={}", body, orgId, timestamp, aesKey)).toLowerCase();

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("orgId", orgId);
        paramMap.put("timestamp", timestamp);
        paramMap.put("sign", sign);
        paramMap.put("body", body);

        log.info("【桔铀花下游双授权】撞库开始【queryUrl】{}【bizMap】{}【paramMap】{}", queryUrl, JSON.toJSONString(bizMap), JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(queryUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        JSONObject resultObject = JSON.parseObject(result);


        log.info("【桔铀花下游双授权】撞库结束【resultDes】{}", resultObject.toJSONString());

        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");

        pushApiResult.setCode(code + "");
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(bizMap));
        pushApiResult.setResultInfo(result);

        if (code == 200) {
            JSONObject data1 = resultObject.getJSONObject("data");
            Integer status = data1.getInteger("status");
            String desc = data1.getString("desc");
            pushApiResult.setCode(code + "|" + status);
            pushApiResult.setMessage(msg + "|" + desc);
            if (status == 1){
                String tid = data1.getString("tid");
                String logo = data1.getString("logo");
                String name = data1.getString("name");
                String companyName = data1.getString("companyName");
                String companyAddress = data1.getString("companyAddress");
                JSONArray protocolList = data1.getJSONArray("protocolList");

                JSONObject data = protocolList.getJSONObject(0);
                String title = data.getString("title");//协议名称
                String link = data.getString("link");//协议地址

                // 撞库成功之后，商户的机构数据存储

                ThirdInfoDTO thirdInfoDTO = new ThirdInfoDTO();
                thirdInfoDTO.setInfoId(Integer.valueOf(pushApiKeyParam.getInfoId()));
                thirdInfoDTO.setInfoName(pushApiKeyParam.getInfoName());
                thirdInfoDTO.setOrderNo(orderNo);
                JSONObject infoObject = new JSONObject();
                infoObject.put("orderNo",tid);
                infoObject.put("productId",tid);
                infoObject.put("productName",name);
                infoObject.put("companyName",companyName);
                infoObject.put("companyLogo",logo);
                infoObject.put("maxLoanAmount","300000");
                infoObject.put("maxLoanRate","24");
                infoObject.put("minLoanRate","15.4");
                infoObject.put("businessInfo",pushApiKeyParam.getInfoName());
                JSONArray jsonArray = new JSONArray();
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("protocalName",title);
                jsonObject.put("protocalUrl",link);
                jsonArray.add(jsonObject);
                infoObject.put("protocalList",jsonArray);
                thirdInfoDTO.setInfoObject(infoObject);

                boolean save = merchantThirdBaseInfoService.saveThirdInfo(thirdInfoDTO);
                if (save){
                    pushApiResult.setPushSuccess(true);
                    pushApiResult.setOutOrderNo(tid);
                    extJson.put("tid", tid);
                }else{
                    pushApiResult.setMessage("保存撞库数据失败");
                }
            }
        }
        return pushApiResult;
    }

    @Override
    public PushApiResult queryApprove(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        return null;
    }

    @Override
    public PushApiResult registerUser(String orderNo, String outOrderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        pushApiResult.setOrderNo(orderNo);

        String tid = extJson.getString("tid");

        String requestUrl = pushApiKeyParam.getRegisterUrl();

        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("tid", tid);
        bizMap.put("mobilePhone", memberSourceInfo.getMobile());
        bizMap.put("cnName", memberSourceInfo.getRealname());


        String aesKey = pushApiKeyParam.getApiKey();
        String body = QiDaiAesUtil.encrypt(JSON.toJSONString(bizMap), aesKey);
        String orgId = pushApiKeyParam.getApiCode();
        Long timestamp = System.currentTimeMillis();
        String sign = SecureUtil.md5(StrUtil.format("body={}&orgId={}&timestamp={}&secret={}", body, orgId, timestamp, aesKey)).toLowerCase();

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("orgId", orgId);
        paramMap.put("timestamp", timestamp);
        paramMap.put("sign", sign);
        paramMap.put("body", body);

        log.info("【桔铀花下游双授权】导单开始【queryUrl】{}【bizMap】{}【paramMap】{}", requestUrl, JSON.toJSONString(bizMap), JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(requestUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();

        JSONObject resultObject = JSON.parseObject(result);


        log.info("【桔铀花下游双授权】导单结束【result】{}", resultObject.toJSONString());


        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");

        pushApiResult.setCode(code + "");
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(bizMap));
        pushApiResult.setResultInfo(result);

        ThirdInfoDTO thirdInfoDTO = new ThirdInfoDTO();
        thirdInfoDTO.setOrderNo(orderNo );
        thirdInfoDTO.setRetCode(String.valueOf(code));
        thirdInfoDTO.setRetMsg(msg);
        thirdInfoDTO.setResultInfo(result);
        thirdInfoDTO.setStatus("FAILED");

        if (code == 200){
            JSONObject data = resultObject.getJSONObject("data");
            Integer status = data.getInteger("status");
            String desc = data.getString("desc");
            pushApiResult.setCode(code + "|" + status);
            pushApiResult.setMessage(msg + "|" + desc);
            if (status == 1){
                thirdInfoDTO.setStatus("SUCCESS");
            }
        }
        merchantThirdBaseInfoService.updateThirdInfo(thirdInfoDTO);
        if (code == 200) {
            JSONObject data = resultObject.getJSONObject("data");
            Integer status = data.getInteger("status");
            if (status == 1){
                pushApiResult.setPushSuccess(true);
                pushApiResult.setSettleFlag(true);
                pushApiResult.setStatus(PushStatusEnum.SUCCESS.getValue());
                return pushApiResult;
            }
        }
        pushApiResult.setPushSuccess(false);
        pushApiResult.setSettleFlag(false);
        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());
        return pushApiResult;
    }

    @Override
    public PushApiResult queryResult(PushQueryParam pushQueryParam, PushApiKeyParam pushApiKeyParam, String extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        return pushApiResult;
    }

    @Override
    public NoticeParamDTO getNoticeResultParam(String infoId, Map<String, String[]> parameterMap, String paramContent) {
        NoticeParamDTO noticeParamDTO = new NoticeParamDTO();
        return noticeParamDTO;
    }

    @Override
    public JSONObject getNoticeResultReturn(Map<String, String[]> parameterMap, String paramContent, JSONObject extObject) {
        JSONObject jsonObject = new JSONObject();
        return jsonObject;
    }

    @Override
    public ProtocolParamResult getProtocolResult(MerchantBaseInfo merchantBaseInfo, MemberSourceInfo memberSourceInfo) {
        ProtocolParamResult paramResult = new ProtocolParamResult();
        return paramResult;
    }

}
